<template>
  <div class="page-container">
    <div class="in-container">
      <AppSearchForm
        @submit="search"
        @reset="reset"
      >
        <el-form-item>
          <el-input
            v-model="query.name"
            clearable
            placeholder="输入标题搜索"
            style="width: 200px"
          />
        </el-form-item>
      </AppSearchForm>
      <div class="btnBox">
        <el-button
          type="primary"
          @click="openDialog"
        > 新增 </el-button>
        <el-button @click="bathDel"> 删除 </el-button>
      </div>
      <el-tabs
        v-model="query.MsgCategoary"
        @tab-change="handleTabClick"
      >
        <el-tab-pane
          label="消息通知"
          name="1"
        ></el-tab-pane>
        <el-tab-pane
          label="系统公告"
          name="2"
        ></el-tab-pane>
      </el-tabs>
      <AppPageTable
        stripe
        :data="tableData.data"
        @change="getList"
        :autostyle="'height: calc(100% - 127px);'"
        :option="tableData.option"
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
        />
        <el-table-column
          prop="title"
          label="标题"
        />
        <el-table-column
          prop="msgCategoary"
          label="消息类型"
        >
          <template #default="scope">
            {{ scope.row.msgCategoary == "1" ? "通知消息" : "系统消息" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sendePerson"
          label="发布人"
        />

        <el-table-column
          prop="msgType"
          label="通知对象"
        >
          <template #default="scope">
            {{ scope.row.msgType == "PUBLIC" ? "全体用户" : "指定用户" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="msgStatus"
          label="发布状态"
        >
          <template #default="scope">
            {{
              scope.row.msgStatus == "0"
              ? "未发布"
              : scope.row.msgStatus == "1"
                ? "已发布"
                : "已撤销"
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="sendTime"
          label="发布时间"
        />
        <el-table-column
          prop="cancelTime"
          label="撤销时间"
        />

        <el-table-column
          label="操作"
          width="130px"
        >
          <template #default="scope">
            <el-button
              @click="takeDetail(scope.row)"
              link
              type="primary"
            >查看</el-button>
            <el-dropdown style="
                margin-left: 10px;
                font-size: 12px;
                color: #409eff;
                line-height: 23px;
              ">
              <span class="el-dropdown-link">
                更多
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-show="scope.row.msgStatus == '0'">
                    <el-dropdown-item @click="sendMSG(scope.row)">发布</el-dropdown-item>
                    <el-dropdown-item @click="updateMSG(scope.row)">修改</el-dropdown-item>
                    <el-dropdown-item @click="deleteMSG(scope.row)">删除</el-dropdown-item>
                  </div>
                  <div v-show="scope.row.msgStatus == '1'">
                    <el-dropdown-item @click="repealMSG(scope.row)">撤销</el-dropdown-item>
                  </div>
                  <div v-show="scope.row.msgStatus == '2'">
                    <el-dropdown-item>暂无</el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </AppPageTable>

      <el-dialog
        width="500px"
        v-model="dialogData.show"
        :title="dialogData.title"
      >
        <el-form
          :model="noticeFormData"
          :rules="noticeFormRules"
          label-width="120px"
          ref="noticeFormRef"
        >
          <el-form-item
            prop="title"
            label="标题"
          >
            <el-input v-model="noticeFormData.title"></el-input>
          </el-form-item>
          <el-form-item
            prop="msgCategoary"
            label="消息类型"
          >
            <el-radio-group v-model="noticeFormData.msgCategoary">
              <el-radio label="1">通知消息</el-radio>
              <el-radio label="2">系统消息</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="msgType"
            label="通告对象类型"
          >
            <el-radio-group v-model="noticeFormData.msgType">
              <el-radio :label="'PUBLIC'">全体用户</el-radio>
              <el-radio :label="'USER'">指定用户</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="指定用户"
            v-show="noticeFormData.msgType == 'USER'"
          >
            <noticeSelectMore
              v-model:tag-data="noticeFormData.inUser"
              ref="noticeSelectMoreRef"
            >
            </noticeSelectMore>
          </el-form-item>

          <el-form-item
            prop="overTime"
            label="有效期截止时间"
          >
            <el-date-picker
              v-model="noticeFormData.overTime"
              type="datetime"
            />
          </el-form-item>
          <el-form-item
            prop="msgContent"
            label="消息内容"
          >
            <el-input
              type="textarea"
              v-model="noticeFormData.msgContent"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              @click="cancelDialog"
              link
            >取消</el-button>
            <el-button
              type="primary"
              @click="submit"
              :loading="dialogData.btnLoading"
            >
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog
        width="800px"
        v-model="contentDialogData.show"
        title="查看详情内容"
      >
        <div class="detail-dialog">
          <div class="header">
            通告对象 -
            {{
              contentDialogData.data.msgType == "PUBLIC"
              ? "全体用户"
              : "指定用户"
            }}
          </div>
          <div class="content">
            <!-- {{ contentDialogData.data }} -->
            {{ contentDialogData.data.userNames.toString() ?? "-" }}
          </div>
        </div>
        <div class="detail-dialog">
          <div class="header">
            <h2>
              {{ contentDialogData.data.title ?? "标题" }}
            </h2>
            <span>
              {{
                `发布人:  ${contentDialogData.data.sendePerson ?? "暂无"
                } , 发布时间:  ${contentDialogData.data.sendTime ?? "暂无"}`
              }}
            </span>
          </div>
          <div class="content">
            {{ contentDialogData.data.msgContent ?? "-" }}
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import noticeSelectMore from "./components/noticeSelectMore.vue";
export default defineComponent({
  components: {
    AppSearchForm,
    AppPageTable,
    noticeSelectMore,
  },
  data() {
    return {
      tableData: {
        data: [],
        option: useTableOption(),
      },
      query: {
        name: "",
        // 消息类型 1:通知消息 2:系统消息
        MsgCategoary: "1",
      },
      dialogData: {
        show: false,
        title: "新增公告",
        btnLoading: false,
      },
      noticeFormData: {
        title: "",
        // 消息类型 1:通知消息 2:系统消息
        msgCategoary: "1",
        // 通告对象类型（USER:指定用户，PUBLIC:全体用户）
        msgType: "PUBLIC",
        overTime: "",
        msgContent: "",
        // 发布状态（0未发布，1已发布，2已撤销）
        msgStatus: 0,
        // userIds: "",
        // userNames: "",
        //id传值
        userIds: [],
        //仅组件内使用 不传值
        inUser: [],
        //仅接受 不传值
        users: [],
      },
      noticeFormRules: {
        title: [{ required: true, message: "请输入标题", trigger: "change" }],
        overTime: [
          { required: true, message: "请输入截止时间", trigger: "change" },
        ],
        msgContent: [
          { required: true, message: "请输入消息内容", trigger: "change" },
        ],
      },
      userSelectData: {
        loading: false,
        data: [],
      },
      userDefaultUserData: [],

      contentDialogData: {
        show: false,
        data: {},
      },
    };
  },
  methods: {

    // 批量删除
    async bathDel() {
      if (this.tableData.option.selected.length == 0) {
        this.$message.warning("请至少选择一条数据");
        return
      };
      let idArray = [];
      this.tableData.option.selected.forEach(item => {
        idArray.push(item.id);
      });
      let res = await this.$http.post("/api/notice/delete", {
        idArray: idArray,
      });
      if (res.status) {
        this.$message.success(res.message);
        this.search();
      } else {
        this.$message.warning(res.message);
      }
    },

    openDialog() {
      this.dialogData.show = true;
    },
    cancelDialog() {
      this.dialogData.show = false;
    },
    search() {
      this.tableData.option.page = 1;
      this.getList();
    },

    getList() {
      this.tableData.option.loading = true;
      this.$http
        .get("/api/notice/query", {
          Title: this.query.name,
          MsgCategoary: this.query.MsgCategoary,
          PageIndex: this.tableData.option.page,
          PageSize: this.tableData.option.pageSize,
        })
        .then((res) => {
          if (res.status == undefined) {
            res.content.forEach((element) => {
              element.inUser = element.users.map((item) => {
                return { id: item.id, label: item.username };
              });
              element.userIds = element.users.map((item) => {
                return item.id;
              });
              element.userNames = element.users.map((item) => {
                return item.username;
              });
            });
            this.tableData.data = res.content;
            this.tableData.option.total = res.totalElements;
          } else {
            this.$message.error(res.message);
          }
        })
        .finally(() => {
          this.tableData.option.loading = false;
        });
    },

    reset() {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 15;
      this.query.name = "";
      this.search();
    },
    handleTabClick(val) {
      this.tableData.option.page = 1;
      this.tableData.option.pageSize = 15;
      this.search();
    },
    async submit() {
      let url = "";
      if (this.noticeFormData.id) {
        url = "/api/notice/edit";
      } else {
        url = "/api/notice/create";
      }
      await this.$refs.noticeFormRef.validate();
      if (this.noticeFormData.msgType == "PUBLIC") {
        this.noticeFormData.userIds = [];
      } else {
        if (this.noticeFormData.inUser.length == 0) {
          this.$message.warning("请至少选择一个指定用户");
          return;
        } else {
          this.noticeFormData.userIds = this.noticeFormData.inUser.map(
            (item) => item.id
          );
        }
      }
      this.dialogData.btnLoading = true;
      this.$http.post(url, this.noticeFormData).then((res) => {
        if (res.status) {
          this.dialogData.show = false;
          this.search();
        }
        this.dialogData.btnLoading = false;
      });
    },
    takeDetail(data) {
      this.contentDialogData.show = true;
      this.contentDialogData.data = data;
      console.log(data);
    },
    sendMSG(data) {
      this.$http
        .post("/api/notice/public", { idArray: [data.id] })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.search();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    updateMSG(data) {
      this.userSelectData.data = this.userDefaultUserData;
      this.noticeFormData = JSON.parse(JSON.stringify(data));
      console.log(typeof this.noticeFormData.userIds);
      // if(typeof this.noticeFormData.userIds =="string"){

      // }
      // this.noticeFormData.userIds = this.noticeFormData.userIds=="" ? this.noticeFormData.userIds : this.noticeFormData.userIds.split(",");
      this.dialogData.title = "修改公告";
      this.dialogData.show = true;
    },

    deleteMSG(data) {
      this.$http
        .post("/api/notice/delete", { idArray: [data.id] })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.search();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    repealMSG(data) {
      this.$http
        .post("/api/notice/cancel", { idArray: [data.id] })
        .then((res) => {
          if (res.status) {
            this.$message.success(res.message);
            this.search();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    selectUserData(data) {
      this.userSelectData.loading = true;
      this.$http
        .get("/api/user/query", {
          KeyWords: data,
          PageIndex: 1,
          PageSize: 50,
        })
        .then((res) => {
          this.userSelectData.data = res.content;
          this.userSelectData.loading = false;
        });
    },
    selectDefaultUserData() {
      this.$http
        .get("/api/user/query", {
          KeyWords: "",
          PageIndex: 1,
          PageSize: 100,
        })
        .then((res) => {
          this.userDefaultUserData = res.content;
        });
    },
  },
  watch: {
    "dialogData.show"(newVal) {
      if (!newVal) {
        this.noticeFormData = {
          title: "",
          msgCategoary: 1,
          msgType: "PUBLIC",
          overTime: "",
          msgContent: "",
          msgStatus: 0,
          userIds: "",
        };
        this.$refs.noticeSelectMoreRef.resetDefault();
        this.$nextTick(() => {
          this.$refs.noticeFormRef.resetFields();
        });
      }
    },
  },
  created() {
    this.search();
    this.selectDefaultUserData();
    this.selectUserData("");
  },
});
</script>

<style lang="scss" scoped>
.btnBox {
  margin-bottom: 8px;
}

:deep(.el-dropdown-link) {
  display: inline-flex;
  align-items: center;
  outline: none;
}

.detail-dialog {
  border-radius: 4px;
  border: 2px solid rgb(232, 232, 232);
  padding: 8px;

  .header {
    padding-bottom: 8px;
    font-size: 14px;
    border-bottom: 1px solid rgb(232, 232, 232);

    h2 {
      margin-bottom: 16px;
    }
  }

  .content {
    padding-top: 8px;
  }
}

.detail-dialog:first-child {
  margin-bottom: 8px;
}
</style>
